<template>
	<view class="forget-container">
		<!-- 背景动画元素 -->
		<view class="bg-animation">
			<view class="circle circle-1"></view>
			<view class="circle circle-2"></view>
			<view class="circle circle-3"></view>
			<view class="sparkle" v-for="(sparkle, index) in sparkles" :key="index" :style="sparkle.style"
				:class="'sparkle-' + (index % 3 + 1)"></view>
		</view>

		<!-- 主内容区域 -->
		<scroll-view class="main-content" scroll-y>
			<!-- 密码重置卡片 -->
			<view class="reset-card" :style="{ transform: `translateY(${cardOffset}px)` }">
				<!-- Logo区域 -->
				<view class="logo-area">
					<image class="logo" src="/static/logo.png" mode="aspectFit"></image>
					<text class="title">找回密码</text>
					<text class="subtitle">验证身份后重置密码</text>
				</view>

				<!-- 验证表单 -->
				<view class="form-container" v-if="!isVerified">
					<!-- 手机号输入 -->
					<view class="form-item" :class="{ 'input-active': isPhoneFocused }">
						<uni-icons type="phone" size="22" color="#7a8cb1" class="icon"></uni-icons>
						<input class="input" type="number" v-model="phone" placeholder="请输入注册手机号" maxlength="11"
							@focus="isPhoneFocused = true" @blur="isPhoneFocused = false" />
					</view>

					<!-- 姓名输入 -->
					<view class="form-item" :class="{ 'input-active': isNameFocused }">
						<uni-icons type="person" size="22" color="#7a8cb1" class="icon"></uni-icons>
						<input class="input" type="text" v-model="name" placeholder="请输入注册姓名"
							@focus="isNameFocused = true" @blur="isNameFocused = false" />
					</view>

					<!-- 乡镇显示（不可选） -->
					<view class="form-item">
						<uni-icons type="location" size="22" color="#7a8cb1" class="icon"></uni-icons>
						<input class="input" type="text" value="王打卦镇" placeholder="乡镇" disabled />
					</view>

					<!-- 村庄选择 -->
					<view class="form-item-selector" @click="showVillagePicker = true">
						<uni-icons type="home" size="22" color="#7a8cb1" class="icon"></uni-icons>
						<view class="input-display">
							{{ selectedVillage || '请选择注册村庄' }}
						</view>
						<uni-icons type="arrowdown" size="16" color="#7a8cb1" class="arrow"></uni-icons>
					</view>

					<!-- 验证按钮 -->
					<button class="verify-btn" @click="handleVerify" :class="{ 'btn-active': isVerifyValid }"
						hover-class="btn-hover">
						<text v-if="!isVerifying">验证身份</text>
						<view v-else class="loading">
							<view class="dot dot-1"></view>
							<view class="dot dot-2"></view>
							<view class="dot dot-3"></view>
						</view>
					</button>

					<!-- 返回登录 -->
					<view class="back-link">
						<text>想起密码了？</text>
						<text class="link-text" @click="navToLogin">返回登录</text>
					</view>
				</view>

				<!-- 密码重置表单 -->
				<view class="reset-form" v-else>
					<!-- 成功验证提示 -->
					<view class="success-tip">
						<uni-icons type="checkmarkempty" size="40" color="#4CAF50" class="success-icon"></uni-icons>
						<text class="success-text">身份验证成功</text>
					</view>

					<!-- 新密码输入 -->
					<view class="form-item" :class="{ 'input-active': isNewPwdFocused }">
						<uni-icons type="locked" size="22" color="#7a8cb1" class="icon"></uni-icons>
						<input class="input" type="text" v-model="newPassword" placeholder="请输入新密码"
							@focus="isNewPwdFocused = true" @blur="isNewPwdFocused = false" />
					</view>

					<!-- 确认密码 -->
					<view class="form-item" :class="{ 'input-active': isConfirmPwdFocused }">
						<uni-icons type="locked" size="22" color="#7a8cb1" class="icon"></uni-icons>
						<input class="input" type="text" v-model="confirmPassword" placeholder="请再次输入新密码"
							@focus="isConfirmPwdFocused = true" @blur="isConfirmPwdFocused = false" />
					</view>

					<!-- 重置按钮 -->
					<button class="reset-btn" @click="handleReset" :class="{ 'btn-active': isResetValid }"
						hover-class="btn-hover">
						<text v-if="!isResetting">重置密码</text>
						<view v-else class="loading">
							<view class="dot dot-1"></view>
							<view class="dot dot-2"></view>
							<view class="dot dot-3"></view>
						</view>
					</button>
				</view>
			</view>
		</scroll-view>

		<!-- 村庄选择器 -->
		<view class="custom-picker" v-if="showVillagePicker">
			<view class="picker-mask" @click="showVillagePicker = false"></view>
			<view class="picker-content">
				<view class="picker-header">
					<text class="picker-title">选择村庄</text>
					<text class="picker-close" @click="showVillagePicker = false">×</text>
				</view>
				<scroll-view class="picker-list" scroll-y>
					<view class="picker-item" v-for="(village, index) in villages" :key="index"
						:class="{ 'item-active': selectedVillage === village }" @click="selectVillage(village)">
						<text>{{ village }}</text>
						<uni-icons v-if="selectedVillage === village" type="checkmarkempty" size="20" color="#4a6baf"
							class="check-icon"></uni-icons>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>
<script>
import { globalVariable } from '../../configMy.js';

export default {
  data() {
    return {
      phone: '',
      name: '',
      selectedVillage: '',
      newPassword: '',
      confirmPassword: '',
      isPhoneFocused: false,
      isNameFocused: false,
      isNewPwdFocused: false,
      isConfirmPwdFocused: false,
      isVerifying: false,
      isResetting: false,
      isVerified: false,
      showVillagePicker: false,
      cardOffset: 0,
      sparkles: [],
      villages: [
        "大辛村", "李孟楼村", "官庄村"
      ]
    }
  },
  computed: {
    isVerifyValid() {
      return (
        this.phone &&
        this.name &&
        this.selectedVillage
      );
    },
    isResetValid() {
      return (
        this.newPassword &&
        this.confirmPassword &&
        this.newPassword === this.confirmPassword
      );
    }
  },
  mounted() {
    this.startSparkleAnimation();
    // 尝试从缓存加载手机号
    const cachedUser = uni.getStorageSync('userInfo');
    if (cachedUser && cachedUser.phone) {
      this.phone = cachedUser.phone;
    }
  },
  methods: {
    startSparkleAnimation() {
      // 创建闪亮的星星元素
      for (let i = 0; i < 10; i++) {
        this.sparkles.push({
          style: {
            left: `${Math.random() * 100}%`,
            top: `${Math.random() * 100}%`,
            animationDelay: `${Math.random() * 2}s`
          }
        });
      }
    },

    selectVillage(village) {
      this.selectedVillage = village;
      this.showVillagePicker = false;
    },

    async handleVerify() {
      // 表单验证
      if (!this.phone) {
        this.shakeForm();
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return;
      }

      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        this.shakeForm();
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        });
        return;
      }

      if (!this.name) {
        this.shakeForm();
        uni.showToast({
          title: '请输入姓名',
          icon: 'none'
        });
        return;
      }

      if (!this.selectedVillage) {
        this.shakeForm();
        uni.showToast({
          title: '请选择村庄',
          icon: 'none'
        });
        return;
      }

      this.isVerifying = true;

      try {
        // 构造地址信息
        const address = `王打卦镇${this.selectedVillage}`;
        
        // 调用验证接口
        const response = await uni.request({
          url: globalVariable + '/villager/resetPassword',
          method: 'POST',
          data: {
            phone: this.phone,
            name: this.name,
            address: address
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        const result = response.data;

        if (result.status === 1) {
          // 验证成功
          this.isVerified = true;
          this.playSuccessAnimation();
        } else {
          // 验证失败
          this.shakeForm();
          uni.showToast({
            title: result.message || '验证失败，信息不匹配',
            icon: 'none'
          });
        }
      } catch (err) {
        console.error('验证出错:', err);
        uni.showToast({
          title: '验证失败，请稍后再试',
          icon: 'none'
        });
      } finally {
        this.isVerifying = false;
      }
    },

    async handleReset() {
      // 表单验证
      if (!this.newPassword) {
        this.shakeForm();
        uni.showToast({
          title: '请输入新密码',
          icon: 'none'
        });
        return;
      }

      if (!this.confirmPassword) {
        this.shakeForm();
        uni.showToast({
          title: '请确认新密码',
          icon: 'none'
        });
        return;
      }

      if (this.newPassword !== this.confirmPassword) {
        this.shakeForm();
        uni.showToast({
          title: '两次密码不一致',
          icon: 'none'
        });
        return;
      }

      this.isResetting = true;

      try {
        // 构造地址信息
        const address = `王打卦镇${this.selectedVillage}`;
        
        // 调用重置密码接口
        const response = await uni.request({
          url: globalVariable + '/villager/resetPassword2',
          method: 'POST',
          data: {
            phone: this.phone,
            name: this.name,
            address: address,
            password: this.newPassword
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        const result = response.data;

        if (result.status === 1) {
          // 重置成功，更新本地缓存
          const cachedUser = uni.getStorageSync('userInfo') || {};
          uni.setStorageSync('userInfo', {
            ...cachedUser,
            phone: this.phone,
            password: this.newPassword // 注意：实际项目中应该加密存储
          });

          uni.showToast({
            title: result.message || '密码重置成功',
            icon: 'success'
          });

          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/login/login"
            });
          }, 1500);
        } else {
          // 重置失败
          this.shakeForm();
          uni.showToast({
            title: result.message || '密码重置失败',
            icon: 'none'
          });
        }
      } catch (err) {
        console.error('重置密码出错:', err);
        uni.showToast({
          title: '重置密码失败，请稍后再试',
          icon: 'none'
        });
      } finally {
        this.isResetting = false;
      }
    },

    shakeForm() {
      this.cardOffset = -5;
      setTimeout(() => {
        this.cardOffset = 5;
        setTimeout(() => {
          this.cardOffset = -5;
          setTimeout(() => {
            this.cardOffset = 5;
            setTimeout(() => {
              this.cardOffset = 0;
            }, 50);
          }, 50);
        }, 50);
      }, 50);
    },

    playSuccessAnimation() {
      // 添加更多闪亮的星星庆祝验证成功
      for (let i = 0; i < 5; i++) {
        this.sparkles.push({
          style: {
            left: `${Math.random() * 100}%`,
            top: `${Math.random() * 100}%`,
            animationDelay: `${Math.random() * 2}s`
          }
        });
      }
    },

    navToLogin() {
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss" scoped>
	.forget-container {
		width: 100%;
		height: 100vh;
		background-image: radial-gradient(circle at 10% 20%, rgba(255, 15, 51, .1) 0, transparent 20%), radial-gradient(circle at 90% 80%, rgba(8, 255, 111, .1) 0, transparent 20%);

		overflow: hidden;
		position: relative;
	}

	.bg-animation {
		position: absolute;
		width: 100%;
		height: 100%;

		.circle {
			position: absolute;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.3);
			animation: float 15s infinite ease-in-out;
			filter: blur(1px);
			opacity: 0.8;
		}

		.circle-1 {
			width: 300px;
			height: 300px;
			top: 10%;
			left: 5%;
			background: rgba(100, 210, 255, 0.2);
			animation-delay: 0s;
			animation-duration: 20s;
		}

		.circle-2 {
			width: 250px;
			height: 250px;
			bottom: 15%;
			right: 5%;
			background: rgba(120, 220, 160, 0.2);
			animation-delay: 3s;
			animation-duration: 18s;
		}

		.circle-3 {
			width: 200px;
			height: 200px;
			top: 50%;
			left: 20%;
			background: rgba(255, 200, 150, 0.2);
			animation-delay: 6s;
			animation-duration: 16s;
		}

		.sparkle {
			position: absolute;
			width: 10px;
			height: 10px;
			border-radius: 50%;
			pointer-events: none;
			animation: sparkle 2s infinite ease-in-out;

			&.sparkle-1 {
				background: rgba(255, 255, 255, 0.8);
				box-shadow: 0 0 10px 2px rgba(255, 255, 255, 0.8);
			}

			&.sparkle-2 {
				background: rgba(100, 210, 255, 0.7);
				box-shadow: 0 0 10px 2px rgba(100, 210, 255, 0.7);
			}

			&.sparkle-3 {
				background: rgba(255, 220, 100, 0.7);
				box-shadow: 0 0 10px 2px rgba(255, 220, 100, 0.7);
			}
		}
	}

	@keyframes float {

		0%,
		100% {
			transform: translate(0, 0) rotate(0deg);
		}

		25% {
			transform: translate(10px, -15px) rotate(3deg);
		}

		50% {
			transform: translate(-8px, 10px) rotate(-3deg);
		}

		75% {
			transform: translate(5px, -5px) rotate(2deg);
		}
	}

	@keyframes sparkle {

		0%,
		100% {
			transform: scale(1);
			opacity: 0.8;
		}

		50% {
			transform: scale(1.5);
			opacity: 1;
		}
	}

	.main-content {
		width: 100%;
		height: 100%;
		position: relative;
		z-index: 10;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.reset-card {
		width: 85%;
		margin: 30px auto;
		background-color: rgba(255, 255, 255, 0.98);
		border-radius: 24px;
		padding: 30px;
		box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
		transition: transform 0.3s ease-out;

		.logo-area {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-bottom: 30px;

			.logo {
				width: 90px;
				height: 90px;
				margin-bottom: 15px;
				filter: drop-shadow(0 5px 10px rgba(0, 0, 0, 0.1));
			}

			.title {
				font-size: 22px;
				font-weight: bold;
				color: #4a6baf;
				margin-bottom: 8px;
				letter-spacing: 1px;
			}

			.subtitle {
				font-size: 14px;
				color: #7a8cb1;
				letter-spacing: 1px;
			}
		}
	}

	.form-container,
	.reset-form {
		.form-item {
			display: flex;
			align-items: center;
			background-color: #f8f9fa;
			border-radius: 50px;
			padding: 12px 22px;
			margin-bottom: 20px;
			transition: all 0.3s;
			border: 1px solid #e1e6eb;
			position: relative;

			&.input-active {
				border-color: #4a6baf;
				box-shadow: 0 0 0 2px rgba(74, 107, 175, 0.2);
			}

			.icon {
				margin-right: 12px;
				opacity: 0.8;
			}

			.input {
				flex: 1;
				height: 40px;
				font-size: 16px;
				color: #333;
			}
		}

		/* 村庄选择器特殊样式 */
		.form-item-selector {
			display: flex;
			align-items: center;
			background-color: #f8f9fa;
			border-radius: 50px;
			padding: 12px 22px;
			margin-bottom: 20px;
			transition: all 0.3s;
			border: 1px solid #e1e6eb;
			position: relative;

			.icon {
				margin-right: 12px;
				opacity: 0.8;
			}

			.input-display {
				flex: 1;
				height: 40px;
				line-height: 40px;
				font-size: 16px;
				color: #333;
			}

			.arrow {
				margin-left: 10px;
				opacity: 0.7;
			}
		}
	}

	.verify-btn,
	.reset-btn {
		width: 100%;
		height: 52px;
		background: linear-gradient(to right, #4a6baf, #6a8ccc);
		color: white;
		border-radius: 50px;
		font-size: 18px;
		font-weight: bold;
		border: none;
		margin-top: 15px;
		transition: all 0.3s;
		box-shadow: 0 8px 20px rgba(74, 107, 175, 0.3);
		display: flex;
		justify-content: center;
		align-items: center;
		overflow: hidden;

		&.btn-active {
			background: linear-gradient(to right, #6a8ccc, #4a6baf);
		}

		&.btn-hover {
			transform: translateY(-2px);
			box-shadow: 0 12px 25px rgba(74, 107, 175, 0.4);
		}

		.loading {
			display: flex;
			align-items: center;
			justify-content: center;

			.dot {
				width: 8px;
				height: 8px;
				background: white;
				border-radius: 50%;
				margin: 0 4px;
				animation: bounce 1.5s infinite ease-in-out;
			}

			.dot-1 {
				animation-delay: 0s;
			}

			.dot-2 {
				animation-delay: 0.2s;
			}

			.dot-3 {
				animation-delay: 0.4s;
			}
		}
	}

	@keyframes bounce {

		0%,
		100% {
			transform: translateY(0);
		}

		50% {
			transform: translateY(-5px);
		}
	}

	.back-link {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 20px;
		font-size: 14px;
		color: #7a8cb1;

		.link-text {
			color: #4a6baf;
			margin-left: 5px;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				bottom: -2px;
				left: 0;
				width: 0;
				height: 1px;
				background: #4a6baf;
				transition: width 0.3s;
			}

			&:active {
				&::after {
					width: 100%;
				}
			}
		}
	}

	.success-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 30px;
		animation: fadeIn 0.5s ease-out;

		.success-icon {
			margin-bottom: 10px;
			animation: bounceIn 0.5s ease-out;
		}

		.success-text {
			font-size: 18px;
			color: #4CAF50;
			font-weight: bold;
		}
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(10px);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	@keyframes bounceIn {
		0% {
			transform: scale(0.8);
			opacity: 0;
		}

		50% {
			transform: scale(1.1);
		}

		100% {
			transform: scale(1);
			opacity: 1;
		}
	}

	/* 自定义选择器样式 */
	.custom-picker {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 999;
		display: flex;
		justify-content: center;
		align-items: flex-end;

		.picker-mask {
			position: absolute;
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.5);
		}

		.picker-content {
			width: 100%;
			max-height: 70vh;
			background: #fff;
			border-radius: 24px 24px 0 0;
			padding-bottom: env(safe-area-inset-bottom);
			z-index: 1000;
			animation: slideUp 0.3s ease-out;
			box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.1);
		}

		.picker-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20px;
			border-bottom: 1px solid #f0f0f0;

			.picker-title {
				font-size: 18px;
				font-weight: bold;
				color: #333;
			}

			.picker-close {
				font-size: 24px;
				color: #999;
				padding: 10px;
			}
		}

		.picker-list {
			max-height: 60vh;
			padding: 10px 0;
		}

		.picker-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 15px 25px;
			font-size: 16px;
			color: #333;
			transition: all 0.2s;

			&.item-active {
				background-color: #f5f7ff;
			}

			&:active {
				background-color: #f0f2ff;
			}

			.check-icon {
				margin-left: 10px;
			}
		}
	}

	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}

		to {
			transform: translateY(0);
		}
	}
</style>